<template>
  <el-timeline class="ps-0">
    <el-timeline-item v-for="noteDbDoc in props.noteDbDocList" :key="noteDbDoc._id"
      :timestamp="formatTimestamp(noteDbDoc.updatedAt)" placement="top">
      <el-card>
        <div class="flex">
          <div class="flex-1">
            <QuillEditor theme="bubble" :content="noteDbDoc.content" contentType="html" :enable="false" readOnly />
          </div>
          <div>
            <el-dropdown @command="handleCommand">
              <el-button text :icon="MoreFilled">
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{
                    action: 'delete',
                    noteDbDoc: noteDbDoc
                  }">
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item :command="{
                    action: 'copy',
                    noteDbDoc: noteDbDoc
                  }">
                    复制
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-card>
    </el-timeline-item>
  </el-timeline>
</template>
<script lang="ts" setup>
import { NoteDbDoc } from '../../store';
import dayjs from 'dayjs';
import { MoreFilled } from '@element-plus/icons-vue'
import storeService from '../../store';
import { ElMessage } from 'element-plus'
import { QuillEditor } from '@vueup/vue-quill'

const props = defineProps<{
  noteDbDocList: Array<NoteDbDoc>
}>()

const emits = defineEmits<{
  (e: 'afterDelete', noteDbDoc: NoteDbDoc): void
}>()

const formatTimestamp = (timestamp: number) => {
  // If today, just show time
  if (dayjs().isSame(timestamp, 'day')) {
    return dayjs(timestamp).format('HH:mm:ss')
  }
  // If yesterday, show '昨天' + time
  if (dayjs().subtract(1, 'day').isSame(timestamp, 'day')) {
    return `昨天 ${dayjs(timestamp).format('HH:mm:ss')}`
  }
  // If this year, show 'MM-DD' + time
  if (dayjs().isSame(timestamp, 'year')) {
    return dayjs(timestamp).format('MM-DD HH:mm:ss')
  }
  // If not this year, show 'YYYY-MM-DD' + time
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

const handleCommand = async (command: {
  action: 'delete' | 'copy'
  noteDbDoc: NoteDbDoc
}) => {
  console.log({
    component: '<NoteList />',
    function: 'handleCommand',
    command
  })

  console.log(command.noteDbDoc._id)

  switch (command.action) {
    case 'delete':
      await storeService.delete(command.noteDbDoc._id)
      ElMessage.success('删除成功')
      emits('afterDelete', command.noteDbDoc)
      break;
    case 'copy':
      utools.copyText(command.noteDbDoc.content)
      ElMessage.success('复制成功')
      break;
  }
}

</script>